from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from rest_framework.generics import RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from rest_framework import serializers, mixins
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from django_redis import get_redis_connection

from .models import User
from goods.models import SKU
from .serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer, UserAddressSerializer, AddressTitleSerializer, UserBrowseHistorySerializer
from goods.serializers import SKUSerializer
from . import constants


# Create your views here.
class UsernameCountView(APIView):
    """
    用户姓名重复检测
    """
    def get(self, request, username):
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }
        return Response(data)


class MobileCountView(APIView):
    """
    手机号重复检测
    """
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }
        return Response(data)


class UserView(CreateAPIView):
    """
    注册
    """
    serializer_class = CreateUserSerializer


class UserDetailView(RetrieveAPIView):
    """
    个人中心基本信息展示
    1.登录用户才能访问,指定权限
    2.前端没有传入主键到视图中,get_object方法无法获取pk,所以要重写get_object方法
    """
    permission_classes = [IsAuthenticated]

    serializer_class = UserDetailSerializer

    def get_object(self):
        """
        返回当前登录的user信息
        :return:
        """
        return self.request.user


class EmailView(UpdateAPIView):
    """
    添加邮箱
    """
    permission_classes = [IsAuthenticated]

    serializer_class = EmailSerializer

    def get_object(self):
        """
        返回当前登录的user信息
        :return:
        """
        return self.request.user


class VerifyEmail(APIView):
    """
    验证邮箱,通过获取的token读取出user_id,查询出当前要激活的用户
    将用户的email_active置为true
    """
    def get(self, request):
        # 获取的token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)
        # 读取出user_id
        # 将用户的email_active置为true
        # 验证token
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({'message': 'OK'})


class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    """
    serializer_class = UserAddressSerializer
    permissions = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


# 浏览记录,保存数据到redis数据库
class UserBrowsHistoryView(CreateAPIView):
    """用户浏览记录接口"""

    # 指定权限：必须登录用户才能保存浏览记录
    permission_classes = [IsAuthenticated]
    # 指定序列化器
    serializer_class = UserBrowseHistorySerializer

    def get(self, request):
        """读取用户浏览记录
        """
        # 创建连接到redis的对象
        redis_conn = get_redis_connection('history')

        # 读取出所有的sku_id信息
        sku_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)

        # sku模型对象的容器
        sku_list = []
        # 遍历sku_ids，取出sku_id,查询sku
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)

        # 将sku_listJ进行序列化
        serializer = SKUSerializer(sku_list, many=True)

        return Response(serializer.data)




